<#import "inc/macro-page.html" as panel>
<#import "macro-filter-card-box.html" as seachpanel>
<#escape x as x?html>
<@panel.header "专业化人岗适配预警" "">
<style>
.table.content-center th,
.table.content-center td{
	text-align:center;
}
.table-bordered th,
.table-bordered td {
    border: 1px solid #bcc4cd !important;
}
</style>
</@panel.header>
<@panel.body>
<div id="export-container" style="display:none;"></div>
<!-- Bread crumb -->
<div class="row page-titles">
    <div class="col-md-5 align-self-center">
        <h3>专业化人岗适配预警</h3> </div>
    <div class="col-md-7 align-self-center">
        <div class="page-nav-bar">
           <button class="btn btn-info btn-click-bind" data-sign="11">制定特定人岗适配模型</button>
           <button class="btn btn-info btn-click-bind" data-sign="12">特定人员人岗适配分析</button>
           <button class="btn btn-info btn-click-bind" data-sign="21">制定通用人岗适配模型</button>
           <button class="btn btn-inverse btn-click-bind" data-sign="22" disabled>通用人岗适配分析</button>
        </div>
    </div>
</div>
<!-- End Bread crumb -->
<!-- Container fluid  -->
<div class="container-fluid">
    <!-- Start Page Content -->
    <div class="card">
		<div class="custom-card-header quick-bar">
			<div class="hint">通用人员筛选</div>
			<@seachpanel.filterbox></@seachpanel.filterbox>
			<button id="id-export-file" type="button" class="btn btn-dark btn-outline btn-sm m-l-10" title="导出"><i class="fa fa-share-square-o"></i></button>
		</div>
         <div class="card-body">
	                <ul class="nav nav-tabs  m-t-40" role="tablist">
	                	<li class="nav-item">
	                		<a class="nav-link active" data-toggle="tab" href="#id-tab-diagram" role="tab">
	                		 <span class="hidden-xs-down">人岗适配对比分析</span>
	                		</a>
	                	</li>
	                	<li class="nav-item">
	                		<a class="nav-link" data-toggle="tab" href="#id-tab-table" role="tab">
	                		 <span class="hidden-xs-down">人岗适配值分析</span>
	                		</a>
	                	</li>
	                </ul>
	                <div class="tab-content tabcontent-border">
	                   <div class="tab-pane active" id="id-tab-diagram" role="tabpanel">
					         <div id="id-chart-container" class="row m-t-30"></div>
					         <div id="id-clone-area"></div>
				       </div>
                       <div class="tab-pane" id="id-tab-table" role="tabpanel">
                          <table id="id-user-table" class="table table-bordered content-center m-t-30"  cellspacing="0" width="100%">
                              <thead>
                                  <tr>
                                      <th>ERP编号</th>
                                      <th>姓名</th>
                                      <th>专业性(Z)</th>
                                      <th>创效性(C)</th>
                                      <th>可塑性(P)</th>
                                      <th>稳定性(W)</th>
                                      <th>相容性(X)</th>
                                      <th>适应性(S)</th>
                                      <th>适配度</th>
                                      <th>自然排序</th>
                                  </tr>
                              </thead>
                           </table>
                       </div>
	                </div>
	    	 </div>
	 	</div>
	</div>
    <!-- End PAge Content -->
</div>
<!-- End Container fluid  -->
</@panel.body>
<@panel.footer>
<script type="text/javascript" src="${ROOT}/mind/js/plugins/alangyun-filterbox.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/datatables/datatables.min.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/datatables/jquery.dataTables.zh-CN.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/echart/echarts.min.5.4.0.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/format/jquery.formatter.js"></script>
<script type="text/javascript">

// word导出事件
document.getElementById('id-export-file').addEventListener('click', function() {
    // Ensure echarts charts have finished rendering
    setTimeout(() => {
        var charts = document.querySelectorAll('canvas');
        charts.forEach(chart => {
            var dataURL = chart.toDataURL();
            var imgTag = '<img src="' + dataURL + '" width="500" />';
            chart.insertAdjacentHTML('beforebegin', imgTag);
            chart.style.display = 'none'; // Hide the original canvas
        });

        // Create a temporary container for the export
        var exportContainer = document.createElement('div');
        exportContainer.id = 'export-container';
        exportContainer.style.width = '100%';

        // Clone ECharts charts
        var chartContainer = document.getElementById('id-chart-container').cloneNode(true);
        exportContainer.appendChild(chartContainer);

        // Clone user table and add border class
        var clonedTable = document.getElementById('id-user-table').cloneNode(true);
// 直接添加内联样式到每个th和td元素
        clonedTable.querySelectorAll('th, td').forEach(function(cell) {
            cell.style.border = '1px solid #000';
            cell.style.borderCollapse = 'collapse'; // 注意：borderCollapse是CSS属性，不能作为内联样式设置，但这里为了示例而写
            cell.style.textAlign = 'center';
        });
        exportContainer.appendChild(clonedTable);

        // Convert the export container's HTML to a Word document
        var htmlHeader = `
          <!DOCTYPE html>
          <html>
          <head>
            <style>
               table, th, td {
                   border: 1px solid #000;
                   text-align: center;
                   border-collapse: collapse;
               }
            </style>
          </head>
          <body>`;
        var htmlFooter = `
          </body>
          </html>`;
        var htmlContent = htmlHeader + exportContainer.innerHTML + htmlFooter;

        var blob = new Blob([htmlContent], { type: 'application/msword' });
        var url = URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = '通用人岗适配分析.doc';
        a.click();
        URL.revokeObjectURL(url);

        // Clean up by removing the temporary container
        exportContainer.remove();

        // Revert changes made to the document for export
        charts.forEach(chart => {
            chart.previousSibling && chart.previousSibling.remove();
            chart.style.display = 'block'; // Restore the original canvas
        });
    }, 1000); // Adjust the timeout as needed to ensure charts have rendered
});



var standardData = {}
var usersData = []
let spdValues = [];
  $(document).ready(function(){
	  $(".btn-click-bind").click(function() {
		  var val = $(this).data("sign");
		  var ctx = "/w/prof";
		  if(12===val){
			  ctx = "/w/prof12";
		  }else if(21===val){
			  ctx = "/w/prof21";
		  }else if(22===val){
			  ctx = "/w/prof22";
		  }
		  window.location.href="${ROOT}" + ctx;
	  });

		var $userTable=$('#id-user-table').dataTable({
		    "ordering":false,//是否允许排序
		    "searching": false,
		    "bFilter":false,//是否需要过滤
		    "info": false,
		    "paging": false,
		    'bAutoWidth':false,//是否自适应宽度
		    "bDestroy" : true,//是否允许删除时销毁
		    /* 定义列 */
		    "aoColumns": [
	   	        //设置列
	   	        {'mData': 'no','sWidth':'100px', defaultContent: '', 'sClass': 'cell-no-wrap' },
	   	        {'mData': 'name','sWidth':'100px', defaultContent: '', 'sClass': 'cell-no-wrap' },
	   	        {'mData': 'z','sWidth':'90px', defaultContent: '', render: function(value){return $.formatFloat(value, 2);} },
	   	        {'mData': 'c','sWidth':'90px', defaultContent: '', render: function(value){return $.formatFloat(value, 2);} },
	   	        {'mData': 'p','sWidth':'90px', defaultContent: '', render: function(value){return $.formatFloat(value, 2);} },
	   	        {'mData': 'w','sWidth':'90px', defaultContent: '', render: function(value){return $.formatFloat(value, 2);} },
	   	        {'mData': 'x','sWidth':'90px', defaultContent: '', render: function(value){return $.formatFloat(value, 2);} },
	   	        {'mData': 's','sWidth':'90px', defaultContent:'', render: function(value){return $.formatFloat(value, 2);}},
                {
                    'mData': 'suit',
                    'sWidth': '90px',
                    defaultContent: '',
                    render: function(data, type, row, meta) {
                        // 标准分（假设 standardData 是全局变量或在外部定义）
                        const { c, p, s, sinValue, w, x, z } = standardData;
                        const ci = c;
                        const pi = p;
                        const si = s;
                        const wi = w;
                        const xi = x;
                        const zi = z;
                        const num = (zi * ci + ci * pi + pi * wi + wi * xi + xi * si + si * zi) * (Math.sqrt(3) / 2);
                        const formattedNum = parseFloat(num.toFixed(2));

                        // 当前行的人员分
                        const { z: zRow, c: cRow, p: pRow, w: wRow, x: xRow, s: sRow } = row;
                        const sum = (zRow * cRow + cRow * pRow + pRow * wRow + wRow * xRow + xRow * sRow + sRow * zRow) * (Math.sqrt(3) / 2);
                        const formattedSum = parseFloat(sum.toFixed(2));

                        // 当前行的适配度
                        const spd1 = formattedSum / formattedNum;
                        const spd = parseFloat(spd1.toFixed(2));

                        // 将当前行的适配度值存储到全局数组中
                        spdValues[meta.row] = spd;
                        console.log(spd,333333)

                        // 返回当前行的适配度值
                        if (typeof spd != "undefined" && spd > 0 && spd != 'Infinity') {
                            return $.formatFloat(spd, 2) + "%";
                        } else {
                            return "0";
                        }
                    }
                },
	   	        {'mData': 'order','sWidth':'90px', defaultContent: '' }
	   	    ]
		});

	  //分析图
	  var charts = [];
	  var createChart = function(rdChart, title, min, standard, fact){

	    //var dom = document.getElementById(el);
	    //var rdChart = echarts.init(dom);

	    var label=[];
	    var data=[];
	    var colors = [];
	    if(fact){
	    	label.push(fact.name);
	    	colors.push("#ffa206");
	    	data.push({
	    		name: fact.name,
	    		// label: {
	    		// 	show: true,
	    		// 	formatter: function(params){
	    		// 		return $.formatFloat(params.value, 2);
	    		// 	}
	    		// },
	    		areaStyle: {
	    			color: "#ffa206"
	    		},
	    		value: [fact.z, fact.s, fact.x, fact.w, fact.p, fact.c]
	    	});
	    }
	    label.push("标准");
    	colors.push("#58a2eb");
	    data.push({
	    		name: "标准",
	    		// label: {
	    		// 	show: true,
	    		// 	formatter: function(params){
	    		// 		return $.formatFloat(params.value, 2);
	    		// 	}
	    		// },
	    		areaStyle: {
	    			color: "#58a2eb"
	    		},
	    		value: [standard.z, standard.s, standard.x, standard.w, standard.p, standard.c]
		   	 });
	    label.push("下限");
    	colors.push("#ef5350");
	    data.push({
	    		name: "下限",
	    		// label: {
	    		// 	show: true,
	    		// 	formatter: function(params){
	    		// 		return $.formatFloat(params.value, 2);
	    		// 	}
	    		// },
	    		areaStyle: {
	    			color: "#ef5350"
	    		},
	    		value:[min.z, min.s, min.x, min.w, min.p, min.c]
	    });

	    option =  {
	        color: colors,
	        tooltip : {
	            trigger: 'item'
	        },
	        title: {
	        	text: title,
	        	left: 'left'
	        },
	        legend: {
	            x : 'right',
	            data:label
	        },
	        polar : [
	            {
	                indicator : [
                        { text: '专业性(Z)', max: 10},
                        { text: '适应性(S)', max: 10},
                        { text: '相融性(X)', max: 10},
                        { text: '稳定性(W)', max: 10},
                        { text: '可塑性(P)', max: 10},
                        { text: '创效性(C)', max: 10}
	                ]
	            }
	        ],
	        calculable : true,
	        series : [
	            {
	                type: 'radar',
	                data : data
	            }
	        ]
	    };

	    if (option && typeof option === "object") {
	        rdChart.setOption(option, false);
	    }
	    window.addEventListener('resize', rdChart.resize);
	}
	/*
	initRadarChart("radar1", "适岗模型");
	initRadarChart("radar2", "甲适配图");
	initRadarChart("radar3", "乙适配图");
	initRadarChart("radar4", "丙适配图");
	*/

    var viewToPage = function(data){
                console.log(data)
                //更改用户信息
	    		$userTable.fnClearTable();
	    		if(data.users && data.users.length>0){
	    			var tableData = [];
                    standardData = data.standard
                    usersData = data.users
	    			var obj= Object.assign({"no":"&nbsp;","name":"标准-胜任","order":"&nbsp;"}, data.standard);
	    			tableData.push(obj);
	    			obj =Object.assign({"no":"&nbsp;","name":"下限-门槛","order":"&nbsp;"},data.min);
	    			tableData.push(obj);
	    			var index=0;
	    			data.users.forEach(item=>{
	    				tableData.push(Object.assign({"order":(++index)},item));
	    			})
	    			$userTable.fnAddData(tableData);
	    		}
	    		$userTable.fnDraw();
	    		//更改能力表信息
	    		if(charts&&charts.length>0){
	    			charts.forEach(item=>{
	    				window.removeEventListener('resize', item.resize);
	    			})
	    		}
	    		$("#id-chart-container").empty();

	    	    //var dom = document.getElementById(el);
	    	    //var rdChart = echarts.init(dom);
	    		var index = 1;
	    		var elementId ="radar"+  index;
	    		$("#id-chart-container").append('<div class="col-lg-6 m-t-30"><div id="'+elementId+'" style="height: 480px"></div></div>');
	    		var rdChart = echarts.init(document.getElementById(elementId));
	    		createChart(rdChart, "适岗模型", data.min, data.standard, null);
	    		charts.push(rdChart);
	    		if(data.users && data.users.length>0) {
	    			data.users.forEach(factitem=>{
	    				elementId ="radar"+  (++index);
	    	    		$("#id-chart-container").append('<div class="col-lg-6 m-t-30"><div id="'+elementId+'" style="height: 480px"></div></div>');
	    	    		var rdChart = echarts.init(document.getElementById(elementId));
	    	    		createChart(rdChart, factitem.name+"适配图", data.min, data.standard, factitem);
	    	    		charts.push(rdChart);
	    			});
	    		}

    }

    // 导出事件绑定
    // $('#id-export-file').click(function(){
    //
    // 	$('.nav-tabs .nav-item a[href="#id-tab-diagram"]').tab("show");
    // 	var cloneDom2 = $('#id-user-table').clone(true);
    // 	$('#id-clone-area').append(cloneDom2);
    //
    // 	var pdfCanvas = $.fn.pdfcanvas({
    // 		title: '通用人员人岗适配分析',
    // 		direct: 'p',
    // 		keywords: '单位和部门：；岗位类别：',
    // 		afterPrint: function(){
    // 			$('#id-clone-area').html("");
    // 		}
    // 	})
    // 	pdfCanvas.addDom(document.getElementById("id-tab-diagram"));
    // 	pdfCanvas.print();
    //
    // });

    //初始化过滤面板
    $.post('${ROOT}/w/treeNav',function(data, status){
    	if(data.code==="ok"){
			$.fn.filterBox({
				spec: false,
				data: data.data,
				onsubmit: function(form, data){
				    $.post('${ROOT}/w/sumprof',data,function(data, status){
				    	if(data&& data.code === 'ok'){
				    		if(data.data) {
						    	$('.nav-tabs .nav-item a[href="#id-tab-diagram"]').tab("show");
				    			viewToPage(data.data);
				    		}else {
				    			toastr.error("未查到人岗适配资料");
				    		}
				    	} else {
				    		toastr.error(data?data.desc:"获取人岗适配资料失败");
				    	}
				    }, 'json');
				}
			})
    	}
    });

    //先提取数据
    $.post('${ROOT}/w/sumprof','spec=false',function(data, status){
    	if(data&& data.code === 'ok'){
    		if(data.data) {
                const users = data.data.users
                users.forEach((item,index) => {
                    const { c, p, s, sinValue, w, x, z } = data.data.standard;
                    const ci = c;
                    const pi = p;
                    const si = s;
                    const wi = w;
                    const xi = x;
                    const zi = z;
                    const num = (zi * ci + ci * pi + pi * wi + wi * xi + xi * si + si * zi) * (Math.sqrt(3) / 2);
                    const formattedNum = parseFloat(num.toFixed(2));

                    // 当前行的人员分
                    const { z: zRow, c: cRow, p: pRow, w: wRow, x: xRow, s: sRow } = item;
                    const sum = (zRow * cRow + cRow * pRow + pRow * wRow + wRow * xRow + xRow * sRow + sRow * zRow) * (Math.sqrt(3) / 2);
                    const formattedSum = parseFloat(sum.toFixed(2));

                    // 当前行的适配度
                    const spd1 = formattedSum / formattedNum;
                    const spd = parseFloat(spd1.toFixed(2));

                    // 将当前行的适配度值存储到全局数组中
                    spdValues[index] = spd;
                    // 返回当前行的适配度值
                    if (typeof spd !== "undefined" && spd > 0 && spd !== 'Infinity') {
                        item.temp = spd
                    } else {
                        item.temp = ""
                    }

                })
                users.forEach((item,index) => {
                    if(index === data.data.users.length - 1) {
                        item['sp'] = Math.abs(item['temp']  - users[0]['temp']).toFixed(2) + '%'
                    } else {
                        item['sp'] = Math.abs(item['temp'] - users[index + 1]['temp']).toFixed(2) + '%'
                    }
                })
                usersData = [...users]
                console.log(usersData,6666666)
                standardData = data.data.standard

                viewToPage(data.data);
    		}else {
    			toastr.error("未查到人岗适配资料");
    		}
    	} else {
    		toastr.error(data?data.desc:"获取人岗适配资料失败");
    	}
    }, 'json');
  });
</script>
</@panel.footer>
</#escape>